package com.encapi.framework.handler.impl;

import com.encapi.framework.constant.EncapiConstant;
import com.encapi.framework.exception.DecryptBodyException;
import com.encapi.framework.exception.EncryptBodyException;
import com.encapi.framework.exception.ExceptionUtil;
import com.encapi.framework.handler.CryptHandler;
import com.encapi.framework.properties.AesProperties;
import com.encapi.framework.util.AesUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AesCryptHandler implements CryptHandler {

    @Resource
    private AesProperties aesProp;

    @Override
    public String getAlgorithm() {
        return EncapiConstant.ALG_AES;
    }

    @Override
    public String encrypt(String plainText, HttpServletRequest request, HttpHeaders headers) throws EncryptBodyException {
        try {
            return AesUtil.encrypt(plainText, aesProp.getKey(), aesProp.getIv());
        } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidAlgorithmParameterException
                | InvalidKeyException | UnsupportedEncodingException | BadPaddingException
                | IllegalBlockSizeException e) {
            throw ExceptionUtil.buildEncryptEx(
                    "an error has occurred when plain text encrypted with aes algorithm cause by : %s", e.getMessage());
        }
    }

    @Override
    public String decrypt(String cipherText, HttpServletRequest request, HttpHeaders headers) throws DecryptBodyException {
        try {
            return AesUtil.decrypt(cipherText, aesProp.getKey(), aesProp.getIv());
        } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidAlgorithmParameterException
                | InvalidKeyException | UnsupportedEncodingException  | BadPaddingException
                | IllegalBlockSizeException e) {
            throw ExceptionUtil.buildDecryptEx(
                    "an error has occurred when cipher text decrypted with aes algorithm cause by : %s", e.getMessage());
        }
    }

}
